﻿using System.Text;

namespace WXWorkSvc.Common.TagHelpers;

[HtmlTargetElement("tds", Attributes = "asp-for-*")]
[HtmlTargetElement("tds", Attributes = "asp-td-*")]
[HtmlTargetElement("tds", TagStructure = TagStructure.WithoutEndTag)]
public class _TableCellsTagHelper : TagHelper
{
    [HtmlAttributeName(DictionaryAttributePrefix = "asp-td-")]
    public IDictionary<string, string> TDs { get; set; } = new Dictionary<string, string>();
    [HtmlAttributeName(DictionaryAttributePrefix = "asp-for-")]
    public IDictionary<string, ModelExpression> Fors { get; set; } = new Dictionary<string, ModelExpression>();

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagMode = TagMode.StartTagAndEndTag;
        output.TagName = "";
        var tds = new Dictionary<int, string>();

        foreach (var item in Fors)
            tds[int.Parse(item.Key)] = item.Value.Model?.ToString() ?? "";//.GetDisplayName();
        foreach (var item in TDs)
            tds[int.Parse(item.Key)] = item.Value;

        StringBuilder sb = new StringBuilder();
        sb.AppendLine(string.Join("", tds.OrderBy(ii => ii.Key).Select(ii => $"<td>{ii.Value}</td>")));
        output.Content.SetHtmlContent(sb.ToString());
    }
}
